import React, { useState, useEffect } from 'react';
import whitelistData from '../data/whitelist.json';
import './LoginModal.css';

interface LoginModalProps {
  isVisible: boolean;
  onClose: () => void;
  onLoginSuccess: (phone: string) => void;
}

const LoginModal: React.FC<LoginModalProps> = ({
  isVisible,
  onClose,
  onLoginSuccess
}) => {
  const [phone, setPhone] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  // 重置状态
  useEffect(() => {
    if (isVisible) {
      setPhone('');
      setError('');
      setIsLoading(false);
    }
  }, [isVisible]);

  // 验证手机号格式
  const validatePhone = (phoneNumber: string): boolean => {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phoneNumber);
  };

  // 检查白名单
  const checkWhitelist = (phoneNumber: string): boolean => {
    return whitelistData.phones.includes(phoneNumber);
  };

  // 处理登录
  const handleLogin = async () => {
    if (!phone.trim()) {
      setError('请输入手机号');
      return;
    }

    if (!validatePhone(phone)) {
      setError('请输入正确的手机号格式');
      return;
    }

    if (!checkWhitelist(phone)) {
      setError('该手机号暂未获得访问权限，请联系管理员');
      return;
    }

    setIsLoading(true);
    setError('');

    // 模拟登录过程
    try {
      await new Promise(resolve => setTimeout(resolve, 1000));
      onLoginSuccess(phone);
      onClose();
    } catch (err) {
      setError('登录失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  // 处理键盘事件
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleLogin();
    }
    if (e.key === 'Escape') {
      onClose();
    }
  };

  if (!isVisible) return null;

  return (
    <div className="login-modal-overlay" onClick={onClose}>
      <div className="login-modal" onClick={(e) => e.stopPropagation()}>
        <div className="login-modal-header">
          <h2 className="login-title">欢迎使用云建AI</h2>
          <p className="login-subtitle">请输入您的手机号进行验证</p>
          <button className="login-close-btn" onClick={onClose}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </button>
        </div>

        <div className="login-modal-body">
          <div className="login-form">
            <div className="input-group">
              <label className="input-label">手机号</label>
              <div className="phone-input-container">
                <span className="phone-prefix">+86</span>
                <input
                  type="tel"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  onKeyPress={handleKeyPress}
                  placeholder="请输入手机号"
                  className="phone-input"
                  maxLength={11}
                  autoFocus
                />
              </div>
            </div>

            {error && (
              <div className="error-message">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M12 9V13M12 17H12.01M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
                {error}
              </div>
            )}

            <button
              className={`login-btn ${isLoading ? 'loading' : ''}`}
              onClick={handleLogin}
              disabled={isLoading || !phone.trim()}
            >
              {isLoading ? (
                <>
                  <div className="loading-spinner"></div>
                  验证中...
                </>
              ) : (
                '立即验证'
              )}
            </button>
          </div>

          {/* <div className="login-footer">
            <p className="login-tip">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z" stroke="currentColor" strokeWidth="2"/>
                <path d="M12 8V12L16 14" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
              仅限白名单用户使用
            </p>
          </div> */}
        </div>
      </div>
    </div>
  );
};

export default LoginModal;
